<template>
  <page-wrap stay-still back hide-tab :title="dynamicTitle" contentWrapColor="#fff">
    <view class="form-wrap" :style="'margin-bottom:' + inputBottom + 'px;'">
      <view class="form-top">
        <view class="form-top-title">{{expId?'编辑':"添加"}}工作经历</view>
        <view class="form-top-subtitle">{{expId?'编辑':"添加"}}工作经历，提高工作匹配率</view>
      </view>
      <u-form :model="form" ref="uForm" label-position="top" class="form">
        <block v-for="(item, index) in formList" :key="index">
          <view class="form-item-wrap" @click.capture="handleSelect($event, item, index)">
            <u-form-item :class="[{ pick: item.comp }, { multiple: item.multiple }]" :label="item.label"
              :prop="item.prop" :border-bottom="!item.hideBorderBottom" :required="item.required">
              <!-- textarea -->
              <!-- <my-textarea v-if="!item.comp && item.type === 'textarea'" class="form-text" :value="form[item.prop]"
                :placeholder="item.inputPlaceholder" :maxlength="item.maxlength" auto-height show-word-limit
                @update:value="handleClear($event, item)" @board-change="handleBottom"></my-textarea> -->
              <u-input v-if="!item.comp && item.type === 'textarea'" :class="[
                  'form-input',
                  { textarea: item.inputType === 'textarea' },
                ]" v-model="form[item.prop]" :disabled="!!item.comp" :placeholder="item.inputPlaceholder"
                :type="item.inputType" :height="item.height" :maxlength="item.maxlength || 150" :clearable="false"
                :id="item.prop" @click="handleTextAreaClick(item)" disabled />
              <u-input v-else :class="[
                  'form-input',
                  { textarea: item.inputType === 'textarea' },
                ]" v-model="form[item.prop]" :disabled="!!item.comp" :placeholder="item.inputPlaceholder"
                :type="item.inputType" :height="item.height" :maxlength="item.maxlength || 150" :clearable="false"
                :id="item.prop" />
              <text v-if="item.multiple">~</text>
              <u-input v-if="item.multiple" class="form-input" v-model="form[item.prop2]" :disabled="!!item.comp"
                :placeholder="item.inputPlaceholder2" :clearable="false" @click="handleMultipleSelect(item)"
                :id="item.prop2" />

              <!-- 下拉选择 -->
              <u-select class="form-select" v-model="showSelect" :list="item.data" v-if="item.comp === 'select'"
                @confirm="handleConfirm($event, item)"></u-select>
              <u-select class="form-select" v-model="showSecret" :list="item.data" v-if="item.comp === 'select2'"
                @confirm="handleConfirm($event, item)"></u-select>
              <!-- 时间选择 -->
              <u-picker class="form-time" mode="time" v-model="showWorkingTime" :params="item.param"
                :start-year="item.start" :end-year="item.end" :default-time="form[tapTarget]"
                v-if="item.comp === 'time'" @confirm="handleConfirm($event, item)"></u-picker>
              <!-- 行业 -->
              <u-select class="form-select" v-model="showTrade" :list="item.data" label-name="totalname"
                value-name="totalid" v-if="item.comp === 'trade'" @confirm="handleConfirm($event, item)"></u-select>
              <!-- <u-popup
                class="form-comp"
                v-model="showTrade"
                mode="bottom"
                z-index="100"
                safe-area-inset-bottom
                v-if="item.comp === 'trade'"
              >
                <view class="u-flex u-row-between btn-group">
                  <text class="cancel" @click="showTrade = false">取消</text>
                  <text
                    class="confirm"
                    type="primary"
                    size="medium"
                    @click="showTrade = false"
                    >保存</text
                  >
                </view>
                <scroll-view scroll-y="true" style="height: 50vh">
                  <trade-filter
                    limit
                    :form-data="[item.activeParent, form[item.propVal]]"
                    :prop-list="item.propList"
                    @confirm="handleReturn(arguments, index)"
                  ></trade-filter>
                </scroll-view>
              </u-popup> -->
              <!-- 职位 -->
              <u-popup class="form-comp" v-model="showPost" mode="bottom" z-index="101" safe-area-inset-bottom
                v-if="item.comp === 'job'">
                <view class="u-flex u-row-between btn-group">
                  <text class="cancel" @click="showPost = false">取消</text>
                  <text class="confirm" type="primary" size="medium" @click="showPost = false">保存</text>
                </view>
                <scroll-view scroll-y="true" style="height: 50vh">
                  <job-classify-filter limit :form-data="form[item.propVal]" :prop-list="item.propList"
                    :tradeId="form.totalid" @confirm="handleReturn(arguments, index)"></job-classify-filter>
                </scroll-view>
              </u-popup>
            </u-form-item>
            <!-- <view v-if="item.showWords" class="content-words"
              >{{
                1000 - ((form[item.prop] && form[item.prop].length) || 0)
              }}字</view
            > -->
          </view>
        </block>
      </u-form>
    </view>
    <view class="page-action">
      <view class="btn-delete" v-if="expId && !isLast">
        <u-button :hair-line="false" :plain="true" :custom-style="btnSaveStyle" @click="handleDelete">删除</u-button>
      </view>
      <view class="btn-save">
        <u-button type="primary" :custom-style="btnStyle" @click="handleSave">保存</u-button>
      </view>
    </view>
  </page-wrap>
</template>

<script>
import JobClassifyFilter from "../components/JobClassifyFilter";
import {
  saveExperience,
  deleteExperience,
  getResumeData,
  getTradeListForWordExperience,
} from "@/api/index";
import { secretList } from "@/utils/data";
import trade from "../../utils/tradeForExp";
import ShareMixin from "@/mixins/share";
import newResumeItem from "@/mixins/newResumeItem";
import { throttle } from "lodash";
import { dealSingleModuleScore } from "@/api/modules/career.js";
export default {
  mixins: [ShareMixin, newResumeItem],
  components: {
    JobClassifyFilter,
  },
  data() {
    return {
      navBarTitle: "工作经历",
      isLast:
        getApp().globalData.userInfo.personWorkArr &&
        getApp().globalData.userInfo.personWorkArr.length <= 1,
      inputBottom: 0,
      expId: "",
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      info: {},
      form: {},
      showSelect: false,
      showSecret: false,
      showTrade: false,
      showWorkingTime: false,
      showPost: false,
      experienceInfo: {},
      formList: [
        {
          label: "公司名称",
          prop: "company",
          inputPlaceholder: "请输入公司名称",
          required: true,
        },
        {
          label: "公司行业",
          prop: "totalname",
          propVal: "totalid",
          inputPlaceholder: "请选择公司行业",
          comp: "trade",
          show: "showTrade",
          // propList: ["totalid", "totalname", "tradeid"],
          // activeParent: "",
          data: trade,
          required: true,
        },
        {
          label: "职位类型",
          prop: "jtzwtype",
          inputPlaceholder: "请选择职位类型",
          comp: "job",
          show: "showPost",
          propList: ["jtzwtypeName", "jtzwtype"],
          required: true,
        },
        {
          label: "职位名称",
          prop: "jtzw",
          inputPlaceholder: "请输入职位名称",
          required: true,
        },
        {
          label: "在职时间",
          multiple: true,
          prop: "startdate",
          prop2: "stopdate",
          inputPlaceholder: "请选择开始时间",
          inputPlaceholder2: "请选择结束时间",
          comp: "time",
          show: "showWorkingTime",
          required: true,
          setProp2: false,
          param: {
            year: true,
            month: true,
            day: true,
            hour: false,
            minute: false,
            second: false,
          },
          start: new Date().getFullYear() - 70,
          end: new Date().getFullYear(),
        },
        {
          label: "工作经历内容",
          prop: "workdesc",
          inputPlaceholder: "请输入工作经历内容和职责",
          type: "textarea",
          maxlength: 1000,
          showWords: true,
          // hideBorderBottom: true,
        },

        {
          label: "公司名称是否保密",
          prop: "companykjName",
          propVal: "companykj",
          inputPlaceholder: "请选择是否保密",
          comp: "select2",
          show: "showSecret",
          data: secretList,
        },
        {
          label: "是否为实习经历",
          prop: "is_practice",
          propVal: "companykj",
          inputPlaceholder: "请选择是否为实习经历",
          comp: "select",
          show: "showSelect",
          data: secretList,
        },
      ],

      btnSaveStyle: {
        border: "none",
        backgroundColor: "#E9ECEF",
      },
      btnStyle: {
        border: "none",
      },
      rules: {
        company: [
          {
            required: true,
            message: "请输入公司名称",
          },
        ],
        totalname: [
          {
            required: true,
            message: "请选择公司行业",
          },
        ],
        jtzwtype: [
          {
            required: true,
            message: "请选择职位类型",
          },
        ],
        jtzw: [
          {
            required: true,
            message: "请输入职位名称",
          },
        ],
        startdate: [
          {
            validator: this.testStartDate,
          },
        ],
      },
      currentItem: null,
      tradeList: [],
      tapTarget: "",
    };
  },
  watch: {
    info: {
      handler(val) {
        if (val.personWorkArr) {
          let item = val.personWorkArr.find((ele) => ele.workId === this.expId);
          this.currentItem = item;
          this.form = {
            workId: item.workId,
            company: item.company,
            companykj: item.companykj,
            companykjName: this.handleCompanyKjName(item.companykj),
            jtzwtype: item.jtzwtype,
            jtzw: item.jtzw,
            totalid: item.totalid,
            totalname: this.handleTotalName(item.totalid),
            tradeid: item.tradeid,
            salarymonth: item.salarymonth,
            startdate: item.startdate,
            stopdate: item.stopdate,
            workdesc: item.workdesc,
            is_practice: item.is_practice == "0" ? "否" : "是",
          };
        }
      },
      deep: true,
      immediate: true,
    },
    showWorkingTime(val) {
      if (!val) {
        this.formList.forEach((item) => {
          if (item.setProp2) {
            item.setProp2 = false;
          }
        });
      }
    },
    inputBottom(val) {
      if (val) {
        this.$nextTick(() => {
          uni.pageScrollTo({
            scrollTop: 99999,
            duration: 0,
          });
        });
      }
    },
  },
  created() {
    this.getTradeList();
  },
  onLoad(options) {
    if (options.id || options.workId) {
      this.expId = options.id || options.workId;
      this.getResumeData();
    }
  },
  onShow() {
    //读取切换页面之后输入的内容
    const newResumeCurrentFormItemInfo = uni.getStorageSync(
      "newResumeCurrentFormItemInfo"
    );

    this.$set(
      this.form,
      newResumeCurrentFormItemInfo.prop,
      newResumeCurrentFormItemInfo.value
    );

    uni.removeStorageSync("newResumeCurrentFormItemInfo");
  },
  methods: {
    //编辑单个简历模块上报
    dealSingleModuleScore() {
      const params = {
        personId: this.personId || uni.getStorageSync("person-id").slice(2),
        resumeModule: 4, //简历模块 1:基本信息 2:求职状态 3:求职意向 4:工作经历 5:项目经验 6：自我评价 7：教育背景 8：个人证书 9：技能特长 10：培训经历 11：校园经历 12：奖项荣誉
      };
      dealSingleModuleScore(params);
    },
    handleTextAreaClick(item) {
      uni.setStorageSync("newResumeCurrentFormItemInfo", {
        ...item,
        value: this.form[item.prop],
      });
      if (item.type == "textarea") {
        uni.navigateTo({
          url: `/pagesSub/newResume/generalTextAreaPage/index`,
        });
      }
    },
    testStartDate(rule, value, callback) {
      if (!value) {
        return callback("请选择开始时间");
      } else if (!this.form.stopdate) {
        return callback("请选择结束时间");
      } else if (value >= this.form.stopdate) {
        return callback("起止时间有误");
      }
      return true;
    },
    handleBottom(e) {
      this.inputBottom = e > 130 ? e - 130 : 0;
    },
    handleClear(e, item) {
      this.$set(this.form, item.prop, e);
    },
    getResumeData() {
      console.log("工作经历获取简历信息", getApp().globalData.resumeInfo);

      if (
        !getApp().globalData.resumeInfo ||
        !getApp().globalData.resumeInfo.Iname_p
      ) {
        uni.showLoading();
        let param = {
          personId: this.personId,
          conditionArr: JSON.stringify({
            is_mp: 1,
          }),
        };
        getResumeData(param)
          .then((res) => {
            this.info = res.data;
          })
          .finally(() => {
            uni.hideLoading();
          });
      } else {
        this.info = JSON.parse(JSON.stringify(getApp().globalData.resumeInfo));
      }
    },
    handleSave: throttle(function () {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.saveExp();
        }
      });
    }, 5000),
    saveExp() {
      let form = this.form;
      if (
        form.startdate > form.stopdate
        // || form.startdate > formatTime(new Date(), "yyyy-MM-dd") ||
        // form.stopdate > formatTime(new Date(), "yyyy-MM-dd")
      ) {
        return uni.showToast({ icon: "none", title: "在职时间有误" });
      }
      let params = {
        person_id: this.personId,
      };

      var conditionArr = {};
      conditionArr.work = {};
      if (form.workId != "undefined") {
        conditionArr.work.workId = form.workId;
      }
      // if (form.stopdate == formatTime(new Date(), "yyyy-MM-dd")) {
      //   form.stopdate = "至今";
      // }
      conditionArr.work.is_practice = form.is_practice == "是" ? "1" : "0";
      conditionArr.work.startdate = form.startdate;
      conditionArr.work.company = form.company;
      conditionArr.work.jtzw = form.jtzw;
      conditionArr.work.stopdate = form.stopdate;
      conditionArr.work.cxz = form.cxz;
      conditionArr.work.salarymonth = form.salarymonth;
      conditionArr.work.workdesc = form.workdesc || "";

      conditionArr.work.tradeid = form.tradeid;
      // 新加参数
      conditionArr.work.jtzwtype = form.jtzwtype; //类别
      conditionArr.work.companykj = "" + form.companykj; //保密
      conditionArr.work.totalid = form.totalid;
      params.conditionArr = JSON.stringify(conditionArr);

      saveExperience(params).then((res) => {
        if (res.code == 200) {
          this.dealSingleModuleScore();
            uni.setStorageSync("resumeUpdated",true);//设置一个标识，在resumeAssesment如果为true才会请求接口
          uni.showToast({
            icon: "none",
            title: "保存成功",
            complete() {
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            },
          });
        } else {
          uni.showToast({ icon: "none", title: res.status_desc });
        }
      });
    },
    handleDelete() {
      uni.showModal({
        title: "温馨提示",
        content: `确认删除工作经历？`,
        success: (modalRes) => {
          if (modalRes.confirm) {
            var params = {
              array: JSON.stringify({
                personId: this.personId,
                workId: this.form.workId,
              }),
            };
            deleteExperience(params).then((res) => {
              if (res.code == 200) {
                this.dealSingleModuleScore();
            uni.setStorageSync("resumeUpdated",true);//设置一个标识，在resumeAssesment如果为true才会请求接口
                uni.showToast({
                  icon: "none",
                  title: "删除成功",
                  complete() {
                    setTimeout(() => {
                      uni.navigateBack();
                    }, 1500);
                  },
                });
              } else {
                uni.showToast({ icon: "none", title: res.status_desc });
              }
            });
          }
        },
      });
    },
    handleSelect($event, item, index) {
      if (item.comp) {
        if (item.comp == "job" && !this.form.totalid) {
          uni.showToast({
            title: "请先选择行业",
            icon: "none",
          });
          return;
        }
        this[item.show] = true;
        this.tapTarget = $event.target.id;
      }
    },
    handleMultipleSelect(item) {
      if (item.multiple) {
        this.$set(item, "setProp2", true);
      }
    },
    handleConfirm(e, item) {
      if (item.propVal == "totalid") {
        this.$set(this.form, "jtzwtype", "");
      }
      if (Array.isArray(e)) {
        this.$set(this.form, item.prop, e[0].label);
        if (item.propVal) {
          this.$set(this.form, item.propVal, e[0].value);
        }
      } else {
        let time = `${e.year}-${e.month}-${e.day}`;
        if (item.setProp2) {
          this.$set(this.form, item.prop2, time);
          this.$set(item, "setProp2", false);
          return;
        }
        this.$set(this.form, item.prop, time);
      }
    },

    handleReturn([data, name], index) {
      if (Array.isArray(name) && Array.isArray(data)) {
        name.forEach((ele, idx) => {
          this.$set(this.form, ele, data[idx]);
        });
        if (!index) {
          this.$set(this.formList[index], "activeParent", data[2]);
        }
      } else {
        this.$set(this.form, name, data);
      }
      this[this.formList[index].show] = false;
    },
    handleCompanyKjName(companykj) {
      let item = secretList.find((ele) => {
        return ele.value == companykj;
      });
      return item ? item.label : "";
    },
    handleTotalName(totalid) {
      let item = this.tradeList.find((ele) => {
        return ele.totalid == totalid;
      });
      return item && item.totalname;
    },
    getTradeList() {
      getTradeListForWordExperience({}).then((res) => {
        if (res && res.data) {
          this.tradeList = res.data;
          this.formList[1].data = this.tradeList;
          if (this.currentItem) {
            this.form.totalname = this.handleTotalName(
              this.currentItem.totalid
            );
          }
        }
      });
    },
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
};
</script>

<style lang="scss">
$img-base-resume: $img-base + "resume/";
.form-wrap {
  flex-grow: 1;
  padding: 32rpx 28rpx 175rpx 32rpx;
  background-color: $uni-bg-color;
  border-radius: $uni-border-radius-big;
  .form-top {
    margin-bottom: 74rpx;
    &-title {
      font-size: 48rpx;
      color: #000000;
      font-weight: bold;
      margin-bottom: 16rpx;
    }
    &-subtitle {
      font-size: 26rpx;
      color: #555555;
    }
  }
  ::v-deep .u-form {
    padding-top: 0;
    // margin: 32rpx 32rpx 0;

    .form-text {
      display: block;
      width: calc(100vw - 128rpx);
      box-sizing: border-box;
      .textarea-input {
        background-color: #f8f9fb;
        border-radius: $uni-border-radius-big;
        word-break: break-all;
        textarea,
        .textarea {
          height: 460rpx !important;
          font-size: $uni-font-size-sm;
          word-break: break-all;
        }
        .placeholder {
          font-size: $uni-font-size-sm;
        }
      }
    }

    .textarea {
      background-color: #f8f9fb;
      border-radius: $uni-border-radius-big;
      .u-input {
        background-color: #f8f9fb;
        border-radius: $uni-border-radius-big;
      }
    }
    .u-input__textarea {
      padding: 24rpx 32rpx;
      font-size: $uni-font-size-nor;
    }

    .content-words {
      margin-right: 10rpx;
      text-align: right;
      color: $uni-text-color-888;
      font-size: $uni-font-size-sm;
    }

    .btn-group {
      padding: 0 24rpx;
      line-height: 102rpx;
      .cancel,
      .confirm {
        padding: 0 16rpx;
      }
    }
    .u-form-item--left__content__label {
      font-size: 28rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #555555;
      line-height: 40rpx;
    }
    .u-input__input {
      font-size: 32rpx !important;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #000000 !important;
      line-height: 44rpx;
    }
  }
}
.page-action {
  position: fixed;
  bottom: 94rpx;
  width: 100vw;
  margin: 0;
  padding: 0rpx 32rpx;
  z-index: 9;
  .btn-delete {
    flex-shrink: 0;
    width: 180rpx;
    margin-right: 40rpx;
  }
  .save-btn {
    flex-shrink: 1;
    // margin: 82rpx 0 4rpx;
    width: 100%;
    border-radius: 16rpx;
  }
}
.u-form-item {
  ::v-deep .u-form-item__body::after {
    top: 64%;
    margin-top: 0rpx;
    background-image: url($img-base + "career/right-arrow.png?v=1");
    width: 24rpx;
    height: 24rpx;
  }
}
</style>
